$(document).ready(function(){
    // Function to populate contact forms
    var populate = function () {
        $("[name='nombre']").val($.Storage.get('nombre'));
        $("[name='email']").val($.Storage.get('email'));
        $("[name='telefono']").val($.Storage.get('telefono'));
    }
    
    // Attempt to populate onLoad
    populate();
    
    // Ajax call when contact form is sent
    $("[id^=button-]").click(function (e) {
        var drawer_id = e.target.id.replace('button', 'drawer')
        var form_id = e.target.id.replace('button', 'form');
        var arr_form = $('#'+form_id).serializeArray();
        var json_form = JSON.stringify(arr_form);
        
        // Store client info in browser
        $.Storage.set({
            "nombre":name = arr_form[1]['value'], 
            "email":name = arr_form[2]['value'], 
            "telefono":name = arr_form[3]['value'] 
        });
        
        // Populate
        populate();
        
        $.post("/rpc", json_form,
            function (data, status) {
                $('#'+form_id).remove();
                $('#'+form_id.replace('form', 'msg')).html("¡Gracias! Nos pondremos en contacto para informarte.");
            }
        );
    });
    
    // highlight and open contact drawer on clicking on a product
    $("[id^=prod-]").click(function (e){
        $(this).toggleClass('glow');
        $(this).toggleClass('highlighted');
        var drawer_name = $(this).attr('id').replace('prod-', 'drawer-');
        $("#"+drawer_name).toggle();
        return false;
    });
    
    // Glow products on hover
    $("[id^=prod-]").hover(
        function () { 
            if(!$(this).hasClass('highlighted')) {
                $(this).addClass('glow')
            }
        },
        function () { $(this).removeClass('glow') }
    );
    
    // preselect last submited values into the ENTRY FORM
    $("#dealer [value='{{entry_form_dealer_selected}}']").attr('selected', 'selected');
    $("#brand [value='{{entry_form_brand_selected}}']").attr('selected', 'selected');
    
    // home logos rollovers
    $('#home-logos > img').hover(
        function() {
            src_orig = $(this).attr('src');
            var src_parts = src_orig.split('/');
            var src_file = src_parts.pop();
            var src_path = src_parts.join('/');
            $(this).attr('src', src_path+'/on_'+src_file);
            $(this).attr('title', $(this).attr('alt'));
        },
        function() {
            $(this).attr('src', src_orig);
            $(this).attr('title', '');
        }
    );
});